package com.example.myapplication.update

import android.app.AlertDialog
import android.app.DownloadManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import com.example.myapplication.util.DateTimeParser
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.Date
import java.util.concurrent.TimeUnit

class AutoUpdateApp(private val context: Context) {
    private var downloadId: Long = 0
    private lateinit var downloadManager: DownloadManager

    companion object {
        private const val TAG = "AutoUpdateApp"
        private const val APK_NAME = "app-release.apk"
        private const val GITEE_RELEASES_URL = "https://gitee.com/api/v5/repos/southwind9984/Hello-Android/releases/latest" // 最新发布
//        https://gitee.com/api/v5/repos/southwind9984/Hello-Android/releases/  //所有发行版
        // 添加这一行：复用 Json 实例
        private val jsonFormat = Json { ignoreUnknownKeys = true }
    }


    /**
     * 检查更新入口方法
     */
    fun checkForUpdate() {
        fetchLatestReleaseInfo()
    }

    /**
     * 从Gitee获取最新发布信息
     */
    private fun fetchLatestReleaseInfo() {
        try {
            val client = OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build()

            val request = Request.Builder()
                .url(GITEE_RELEASES_URL)
                .addHeader("User-Agent", "AutoUpdateApp")
                .build()

            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    Log.e(TAG, "获取版本信息失败", e)
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        if (!response.isSuccessful) {
                            Log.e(TAG, "获取版本信息失败，HTTP状态码: ${response.code}")
                            return
                        }

                        val responseBody = response.body?.string()
                        if (responseBody.isNullOrEmpty()) {
                            Log.e(TAG, "响应体为空")
                            return
                        }
                        Log.i(TAG, "获取版本信息成功: $responseBody")

                        val release = jsonFormat.decodeFromString<ReleaseResponse>(responseBody)

                        // 在主线程中处理UI更新
                        (context as? android.app.Activity)?.runOnUiThread {
                            compareVersionAndShowDialog(release)
                        }
                    } catch (e:  Exception) {
                        Log.e(TAG, "解析JSON失败", e)
                    } catch (e: Exception) {
                        Log.e(TAG, "处理响应失败", e)
                    } finally {
                        response.close()
                    }
                }
            })
        } catch (e: Exception) {
            Log.e(TAG, "网络请求失败", e)
        }
    }

    /**
     * 比较版本并显示更新对话框
     */
    private fun compareVersionAndShowDialog(release: ReleaseResponse) {
        try {
            val currentVersion = getCurrentVersion()
            val latestVersion = release.tagName.removePrefix("v") // 移除可能的"v"前缀

            val isNewVersion = isNewVersionAvailable(currentVersion, latestVersion)

            val isReleaseNewer = isReleaseNewerThanApp(release.createdAt)
            if (isNewVersion || isReleaseNewer) {
                showUpdateDialog(release)
            } else {
                Log.d(TAG, "当前已是最新版本: $currentVersion")
            }
        } catch (e: Exception) {
            Log.e(TAG, "版本比较失败", e)
        }
    }

    /**
     * 获取当前应用版本
     */
    private fun getCurrentVersion(): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            packageInfo.versionName ?: "1.0.0"
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e(TAG, "获取当前版本失败", e)
            "1.0.0"
        }
    }

    /**
     * 比较版本号
     */
    private fun isNewVersionAvailable(current: String, latest: String): Boolean {
        return try {
            val currentParts = current.split(".").map { it.toIntOrNull() ?: 0 }
            val latestParts = latest.split(".").map { it.toIntOrNull() ?: 0 }

            for (i in 0 until maxOf(currentParts.size, latestParts.size)) {
                val curr = currentParts.getOrElse(i) { 0 }
                val latest = latestParts.getOrElse(i) { 0 }

                when {
                    latest > curr -> return true
                    latest < curr -> return false
                }
            }
            false
        } catch (e: NumberFormatException) {
            latest > current
        }
    }

    /**
     * 比较release发布时间是否比应用更新时间晚
     */
    private fun isReleaseNewerThanApp(releaseCreatedAt: String): Boolean {
        return try {
            // 解析release创建时间
            val releaseDate = DateTimeParser.parseIsoDateTime(releaseCreatedAt)

            // 获取应用最后更新时间
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            val appUpdateTime = packageInfo.lastUpdateTime

            Log.i(TAG, "应用最后更新时间: ${DateTimeParser.toLocalString(Date(appUpdateTime))}, 发布时间: ${DateTimeParser.toLocalString(releaseDate)}")
            // 比较时间
            releaseDate.time > appUpdateTime
        } catch (e: Exception) {
            Log.e(TAG, "时间比较失败", e)
            false
        }
    }

    /**
     * 显示更新对话框
     */
    private fun showUpdateDialog(release: ReleaseResponse) {
        val builder = AlertDialog.Builder(context)
        builder.setTitle("发现新版本 (${release.tagName})")
        val formattedBody = release.body.replace("\r\n", "\n").replace("\n", "\n\n")
        // 创建更丰富的消息内容
        val message = """
        检测到新版本 ${release.name}
        
        更新时间: ${DateTimeParser.parseTimeToLocalString(release.createdAt)} 
        
        更新日志:
        $formattedBody
         """.trimIndent()

        builder.setMessage(message)

        // 获取APK下载地址
        val apkUrl = release.assets.firstOrNull { it.name.endsWith(".apk") }?.downloadUrl
            ?: release.assets.firstOrNull()?.downloadUrl

        builder.setPositiveButton("立即更新") { _, _ ->
            if (apkUrl != null) {
                downloadApk(apkUrl)
            } else {
                Toast.makeText(context, "未找到APK下载地址", Toast.LENGTH_SHORT).show()
            }
        }

        builder.setNegativeButton("稍后再说") { dialog, _ ->
            dialog.dismiss()
        }

        builder.setCancelable(true)

        try {
            val dialog = builder.create()
            // 美化对话框
            dialog.setOnShowListener {
                val positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
                val negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                val neutralButton = dialog.getButton(AlertDialog.BUTTON_NEUTRAL)

                // 设置按钮颜色
                positiveButton.setTextColor(ContextCompat.getColor(context, android.R.color.holo_blue_dark))
                negativeButton.setTextColor(ContextCompat.getColor(context, android.R.color.darker_gray))
                neutralButton.setTextColor(ContextCompat.getColor(context, android.R.color.holo_green_dark))
            }
            dialog.show()
        } catch (e: Exception) {
            Log.e(TAG, "显示更新对话框失败", e)
        }
    }

    /**
     * 下载APK文件
     */
    private fun downloadApk(apkUrl: String) {
        try {
            // 删除已存在的旧文件
//            deleteExistingApk()

            Log.i(TAG, "下载APK: $apkUrl")
            val request = DownloadManager.Request(apkUrl.toUri()).apply {
                setTitle("应用更新")
                setDescription("正在下载新版本...")
                setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
                // 设置下载路径，使用私有目录
                setDestinationInExternalFilesDir(
                    context,
                    Environment.DIRECTORY_DOWNLOADS,
                    APK_NAME
                )
                setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI or DownloadManager.Request.NETWORK_MOBILE)
                // 强制使用指定的文件名而不根据内容类型更改扩展名
                addRequestHeader("Accept", "application/vnd.android.package-archive")
                setMimeType("application/vnd.android.package-archive")
            }

            downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            // 开始下载
            downloadId = downloadManager.enqueue(request)


            // todo,不使用动态注册，使用静态注册广播接收器。 修复：添加正确的标志位
/*            val receiverFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                Context.RECEIVER_NOT_EXPORTED
            } else {
                @Suppress("DEPRECATION")
                Context.RECEIVER_EXPORTED
            }
            // 注册下载完成的广播接收器
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.registerReceiver(
                    onDownloadComplete,
                    IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE),
                    receiverFlags
                )
            }*/


            Toast.makeText(context, "开始下载更新...", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.e(TAG, "下载APK失败", e)
            Toast.makeText(context, "下载失败，请稍后重试", Toast.LENGTH_SHORT).show()
        }
    }
}
